package com.sharding.order.common.util;

import com.sharding.order.constant.OrderConstant;
import com.sharding.order.service.user.UserOrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * @author ruyuan
 * redis监听过期key
 */
@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Autowired
    private UserOrderInfoService orderInfoService;

    /**
     * 获得过期的key进行订单取消。
     * ps:进行支付的时候会从将redis中数据删除掉。
     *
     * @param message 入参
     * @param pattern 出参
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取失效的key
        String expiredKey = message.toString();
        if (expiredKey.contains(OrderConstant.OrderRedisKey.PREFIX_KEY)) {
            //切割前缀提取订单号
            String orderNo = expiredKey.substring(expiredKey.indexOf(":") + 1);
            //取消订单
            orderInfoService.redisCancelOrder(orderNo);
            log.info("orderNo:[{}] cancel order", orderNo);
        }
    }

}